﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Tasks.Business;
using Tasks.Common.Entitys;
using System.Collections;
using Tasks.Core;
using Tasks.UI.Models.Power;
using Tasks.UI.Models.Account;
using Tasks.Common;
namespace Tasks.UI.Controllers
{
    public class PowerController : BaseController
    {
        PowerBLL powerBll = BusinessFactory.Power;
        AccountBLL accountBll = BusinessFactory.Account;


        /// <summary>
        /// 显示角色管理界面
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [RequireLogin("power", "role")]
        public ActionResult RoleManage(RoleManageModel model)
        {
            model.PowerRoles = powerBll.GetRoles();
            return View(model);
        }

        /// <summary>
        /// 角色组管理,修改，保存
        /// </summary>
        /// <param name="RoleName">角色名</param>
        /// <param name="Dspt">描述</param>
        /// <param name="RoleID">角色ID</param>
        /// <returns></returns>
        [HttpPost, RequireLogin("power", "role")]
        public ActionResult DoEditRoleInfo(string RoleName, string Dspt, int RoleID)
        {
            try
            {
                ExecuteResult result = new ExecuteResult();
                PowerRole role = new PowerRole();
                role.AppID = 1;
                role.IsPersonal = 0;
                role.Name = RoleName;
                role.Dspt = Dspt;
                if (RoleID > 0)
                {
                    role.RoleID = RoleID;
                    PowerRole editrole = powerBll.GetRole(RoleID);
                    role.State = editrole.State;
                    result = powerBll.ModifyRole(role);
                }
                else
                {
                    role.State = 1;
                    result = powerBll.CreateRole(role);
                }

                return Json(role.RoleID);
            }
            catch (Exception ex)
            {
                return Json(0);
            }
        }
        /// <summary>
        /// 账号管理
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [RequireLogin("account", "view")]
        public ActionResult AccountManage(Tasks.UI.Models.Power.AccountManageModel model)
        {
            model.PageSize = model.PageSize == 0 ? 10 : model.PageSize;
            model.PageIndex = model.PageIndex == 0 ? 1 : model.PageIndex;

            int rowCount = 0;
            PowerRole powerRole = new PowerRole();

            //提取 企业会员账号 
            Hashtable condition = new Hashtable();
            condition["RoleID"] = model.RoleID;
            condition["Name"] = model.Name;
            condition["CategoryID"] = 0;
            condition["ProvinceID"] = 0;
            condition["CityID"] = 0;
            condition["AreaID"] = 0;
            condition["EnterpriseType"] = 0;
            condition["EnterpriseMemberState"] = 0;
            model.EnterpriseList = accountBll.SearchEnterpriseMember(condition, Config.CompanyID, model.PageSize, model.PageIndex, out rowCount);
            if (model.EnterpriseList == null) model.EnterpriseList = new List<EnterpriseMember>();

            model.RowCount = rowCount;
            return View(model);
        }

        /// <summary>
        /// 给对象授权
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ActionName("AssignRole"), HttpPost, RequireLogin("power", "assignrole")]
        public ActionResult DoAssignRole(PowerManageModel model)
        {
            ExecuteResult result = new ExecuteResult();

            string roleIDs = "";
            for (int i = 0; i < model.RoleID.Length; i++)
            {
                roleIDs += model.RoleID[i] + ",";
            }
            roleIDs = roleIDs.TrimEnd(',');//获取选中的角色ID，分配到指定对象身上，用逗号隔开
            result = powerBll.AssignRoleToUser(roleIDs, model.UserID);

            if (result.ResultNo == 1)
            {
                if (!string.IsNullOrWhiteSpace(model.ReturnUrl))
                {
                    return Redirect(model.ReturnUrl);
                }
                else
                {
                    model.MessageType = MessageType.close;
                    model.Message = "成功";

                    return new CloseResult();
                }
            }
            else
            {
                model.Message = result.Message;
                model.MessageType = MessageType.error;
            }

            return AssignRole(model);
        }
        /// <summary>
        /// 显示分配角色窗口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet, RequireLogin("power", "assignrole")]
        public ActionResult AssignRole(PowerManageModel model)
        {
            int a = Config.AdminID;
            model.PowerRoleList = powerBll.GetRoles();
            model.PwUser2RoleList = powerBll.GetRoleByUserID(model.UserID);
            model.chkItemsChecked = new bool[model.PowerRoleList.Count];
            for (int i = 0; i < model.PowerRoleList.Count; i++)
            {
                model.chkItemsChecked[i] = false;
                foreach (PowerUser2Role u2r in model.PwUser2RoleList)
                {
                    if (u2r.RoleID == model.PowerRoleList[i].RoleID)
                    {
                        model.chkItemsChecked[i] = true;
                        break;
                    }
                }
            }
            return View(model);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="RoleID">角色ID</param>
        /// <returns></returns>
        [HttpPost, RequireLogin("power", "role")]
        public ActionResult DoDeleteRole(int RoleID)
        {
            if (RoleID > 0)
            {
                powerBll.DeleteRole(RoleID);
            }
            return RedirectToAction("RoleManage");
        }

        /// <summary>
        /// 对个人权限分配
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        public ActionResult AssignUserPower(int userID, string returnUrl)
        {
            int roleID = 0;

            IList<PowerRole> roles = powerBll.GetPowerRoleByUserID(userID);

            //没有订单个人权限，则添加一个个人权限组
            if (roles.Count == 0 || roles.Count(t => t.IsPersonal == 1) == 0)
            {
                PowerRole role = new PowerRole();
                Account account = new AccountBLL().GetAccount(userID);
                role.Name = account.Name;
                role.AppID = 1;
                role.IsPersonal = 1;
                role.State = 1;
                role.OwnerID = Config.CompanyID;

                //创建新角色
                powerBll.CreateRole(role);
                //分配角色权限
                powerBll.AssignSingleRoleToUser(role.RoleID, userID);
                roleID = role.RoleID;
            }
            else
            {
                roleID = roles.First(t => t.IsPersonal == 1).RoleID;
            }

            //跳转到分配角色组页面
            return RedirectToAction("AssignRolePower", new { RoleID = roleID, ReturnUrl = returnUrl });
        }

        /// <summary>
        ///  显示分配角色权限窗口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet, RequireLogin("power", "role")]
        public ActionResult AssignRolePower(AssignRolePowerModel model)
        {
            if (Config.CurrentOperator.UserID == Config.AdminID)
            {
                model.ModuleList = powerBll.GetModules();
                model.ActionList = powerBll.GetActions(); //获取所有权限动作
                model.Apps = powerBll.GetAllApps();
            }
            else
            {
                model.ModuleList = powerBll.GetModulesByUserID(Config.CurrentOperator.UserID);
                model.ActionList = powerBll.GetActionsByUserID(Config.CurrentOperator.UserID);
                model.Apps = powerBll.GetAppsByUserID(Config.CurrentOperator.UserID);
            }

            IList<PowerRole2Module2Action> module2ActionList = powerBll.Get2Module2ActionByRoleID(model.RoleID); // 获取角色的所有权限，用逗号分隔开
            PowerRole role = powerBll.GetRole(model.RoleID);
            model.RoleName = role.Name;
            foreach (PowerRole2Module2Action pr2 in module2ActionList)
            {
                model.srtActions += pr2.ActionID + ",";
            }
            model.srtActions = "," + model.srtActions;
            model.RoleApps = powerBll.GetAppsByRoleID(model.RoleID);

            return View(model);
        }
        /// <summary>
        ///  给角色分配权限
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ActionName("AssignRolePower"), HttpPost, RequireLogin("power", "role")]
        public ActionResult DoAssignRolePower(AssignRolePowerModel model)
        {
            ExecuteResult result = new ExecuteResult();
            if (model.AppID == null)
                return RedirectToAction("AssignRolePower", new { Message = "请选择应用平台", MessageType = MessageType.error, RoleID=model.RoleID });
            //更新角色的应用程序
            powerBll.ModifyRole2App(model.RoleID, model.AppID);

            string actionIds = "";
            if (model.ActionID != null)
            {
                for (int i = 0; i < model.ActionID.Length; i++)
                {
                    actionIds += model.ActionID[i] + ",";
                }
                actionIds = actionIds.TrimEnd(',');
                result = powerBll.AssignModuleToRole(actionIds, model.RoleID);

            }
            else
            {
                result = powerBll.DeleteModule2Action(model.RoleID);//未选中删除
            }

            if (result.ResultNo == 1)
            {
                if (!string.IsNullOrWhiteSpace(model.ReturnUrl))
                {
                    return Redirect(model.ReturnUrl);
                }
                else
                {
                    model.Message = "操作成功!";
                    model.MessageType = MessageType.close;

                    return new CloseResult();
                }
            }
            else
            {
                model.Message = result.Message;
                model.MessageType = MessageType.error;
            }



            return AssignRolePower(model);
        }

        /// <summary>
        /// 菜单权限分配
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult MenuRolePower(MenuRolePowerModel model)
        {
            if (Config.CurrentOperator.UserID == Config.AdminID)
            {
                model.MenuChild = powerBll.GetChildMenu();//子菜单
                model.MenuParent = powerBll.GetParentMenu();//父菜单
            }
            else
            {
                model.MenuParent = powerBll.GetParentMenuByuserID(Config.CurrentOperator.UserID);
                model.MenuChild = powerBll.GetChildMenuByuserID(Config.CurrentOperator.UserID);//子菜单
            }

            if (model.RoleId != 0)
            {
                model.RoleMenu = powerBll.GetMenuPowerByRoleID(model.RoleId);
                IList<PWRole2Menu> ParentMenu = model.RoleMenu.Where(t => t.ParentID == 0).ToList();
                if (model.RoleMenu != null && model.RoleMenu.Count != 0)
                {
                    for (int i = 0; i < model.RoleMenu.Where(t => t.ParentID == 1).ToList().Count; i++)
                    {
                        model.MenuidStr += "," + model.RoleMenu[i].MenuID;
                    }
                    for (int k = 0; k < ParentMenu.Count; k++)
                    {
                        model.ParentMenuidStr += "," + ParentMenu[k].MenuID;
                    }
                }
                model.MenuidStr = model.MenuidStr == null ? "" : model.MenuidStr + ",";
                model.ParentMenuidStr = model.ParentMenuidStr == null ? "" : model.ParentMenuidStr + ",";
            }
            return View(model);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ActionName("MenuRolePower"), HttpPost()]
        public ActionResult doMenuRolePower(MenuRolePowerModel model)
        {
            ExecuteResult result;
            IList<PWRole2Menu> menuList = new List<PWRole2Menu>();
            if (model.MenuID != null)
            {
                for (int i = 0; i < model.MenuID.Length; i++)
                {
                    PWRole2Menu menu = new PWRole2Menu();
                    menu.MenuID = model.MenuID[i];
                    menu.RoleID = model.RoleId;
                    menu.ParentID = 1;
                    menuList.Add(menu);
                }
                for (int k = 0; k < model.MenuParentID.Length; k++)
                {
                    PWRole2Menu menu2 = new PWRole2Menu();
                    menu2.MenuID = model.MenuParentID[k];
                    menu2.RoleID = model.RoleId;
                    menu2.ParentID = 0;
                    menuList.Add(menu2);
                }
                result = powerBll.SaveMenuPower(menuList, model.RoleId);
                if (result.ResultNo == 1)
                {
                    model.Message = result.Message;
                    model.MessageType = MessageType.correct;
                }
            }
            else
            {
                powerBll.DeleteRole2Menu(model.RoleId);
            }

            return RedirectToAction("MenuRolePower", new { RoleId = model.RoleId, Message = model.Message, MessageType = model.MessageType });
        }

        public ActionResult MenuManage()
        {
            return View();
        }
    }
}
